﻿using System.IO;
using System.Windows;
using System.Windows.Input;
using Creventive.Wpf.ShellFactory.Services;
using Creventive.Wpf.ShellFactory.Workspace;
using Microsoft.Win32;
using MultiMasterView.Modules.Core.TextEditor;
using MultiMasterView.Modules.Core.TextEditor.RuntimeModels;

[assembly: ApplicationViewModel(typeof(TextEditorViewModel), typeof(ITextEditorViewModel))]

namespace MultiMasterView.Modules.Core.TextEditor.RuntimeModels
{
    internal class TextEditorViewModel : ApplicationViewModel, ITextEditorViewModel
    {
        private ModelCommand openCommand;
        private string text = null;

        public TextEditorViewModel(IServiceContainer services)
            : base(services, ApplicationViewModelFlags.None)
        {
            this.openCommand = new ModelCommand(this.Open);
        }

        public ICommand OpenCommand
        {
            get { return this.openCommand; }
        }

        public string Text
        {
            get { return this.text; }
            private set
            {
                if (this.text == value)
                    return;
                this.text = value;
                this.OnTextChanged();
            }
        }

        private void Open()
        {
            // In a real-life application I would encapsulate this dialog into a generic service in the ServiceContainer.
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text Files|*.txt";
            if (openFileDialog.ShowDialog(Application.Current.MainWindow) == true)
                this.Text = File.ReadAllText(openFileDialog.FileName);
        }

        protected virtual void OnTextChanged()
        {
            this.OnPropertyChanged("Text");
        }
    }
}